package com.example.administrator.androidsqlite;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.File;

public class MainActivity extends AppCompatActivity {
    private Button btn1;
    private Button btn2;
    private Button btn3;
    private EditText edtNo;
    private EditText edtName;
    private EditText edtAge;
    private Button btnread;
    private TextView txtdate;
    private SQLiteDatabase db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findView();/*方法一，找到事件*/
        onclickView();/*方法二，点击事件*/

    }
        private void onclickView () {
            btn1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    /*创建数据库*/
                    createopenDB();
                }
            });
            btn2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    /*创建学生列表*/
                    createstudenttable();
                }
            });
            btn3.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    /*创建完之后取出学号，姓名，年龄*/
                    String name = edtName.getText().toString();
                    String no = edtNo.getText().toString();
                    int age = Integer.valueOf(edtAge.getText().toString());
                    /*插入新的学生*/
                    insertStudent(no, name, age);
                }
            });
            btnread.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    /*从数据读取并且显示*/
                    readDate();
                }
            });
        }
    private void findView() {
        btn1 = findViewById(R.id.btn_creatDB);
        btn2 = findViewById(R.id.btn_creatStudenttable);
        btn3 = findViewById(R.id.btn_insertDB);
        edtNo=findViewById(R.id.text_no);
        edtName=findViewById(R.id.text_name);
        edtAge=findViewById(R.id.text_age);
        btnread=findViewById(R.id.btn_read);
        txtdate=findViewById(R.id.txt_date);

    }
    /*cursor读取数据*/
    private void readDate() {
        if(db==null){
            createopenDB();
        }
        Cursor cursor= db.query("student",null,null,
                null,null,null,null);/*游标指向数据集，所以要遍历cursor*/
        StringBuffer buffer=new StringBuffer();
        for (cursor.moveToFirst();!cursor.isAfterLast();cursor.moveToNext()){
            String no=cursor.getString(0);
            String name=cursor.getString(1);
            int age=cursor.getInt(2);
            buffer.append(no).append(" ").append(name).append(" ").append(age).append("\n");
        }
        txtdate.setText(buffer);
    }

    /*插入新的学生*/
    private void insertStudent(String no,String name,int age) {
        if (db == null) {
            createopenDB();
        }
       /* 插入的第一种方法
        String sql = "insert into student values('1713157308','苏晓妮',20)";
        db.execSQL(sql);
        插入的第二种方法
        String sql = "insert into student values('"+no+"','"+name+"',"+age+")";
        db.execSQL(sql);
        使用insert接口*/
        ContentValues values=new ContentValues();/*容器*/
        values.put("stuno",no);/*列名*/
        values.put("name",name);
        values.put("age",age);
          db.insert("student","null",values);
    }
/*创建学生表*/
    private void createstudenttable() {
        /*没有创建这个语句，只能通过MySQL语句进行创建*//*判断db==null*/
        if (db == null) {
            createopenDB();
        }
        /*判断表是否存在*/
        String sql = "create table if not exists student (stuno varchar(20),name varchar(20),age int)";
      db.execSQL(sql);

    }

/*创建数据库并打开*/
    private void createopenDB() {
        String path = getFilesDir().getAbsolutePath() + File.separator + "stu.db";
        /*路径还有创建文件跟名字（stu.db）*/
        Log.e("MainActivity", "path=" + path);
        db = SQLiteDatabase.openOrCreateDatabase(path, null);
    }
}